<template>
  <div class="sandwich-generator" :class="[currentTheme, isDarkMode ? 'dark-mode' : '']">
    <!-- 应用介绍 -->
    <div class="app-intro">
      <h1>创意三明治生成器</h1>
      <p>解决"冰箱的菜怎么吃"的日常痛点！</p>
      <p>只需输入手边食材（如鸡蛋、番茄、芝士），将为您生成创意三明治食谱</p>
    </div>
    <!-- 用户输入模块 -->
    <div class="icons">
        <span class="theme-icon" @click="showThemeDialog = true">🎨</span>
        <span class="theme-icon" @click="selectTheme('theme-food')">🍔</span>
        <span class="theme-icon" @click="selectTheme('theme-fresh')">🍃</span>
        <span class="theme-icon" @click="selectTheme('theme-warm')">☀️</span>
        <span class="theme-icon" @click="toggleDarkMode">{{ isDarkMode ? '🌞' : '🌙' }}</span>
        <span class="theme-icon" @click="showHistoryDialog = true">📜</span>
      </div>
      <div class="input-section">
      <!-- 食谱类型选择 -->
      <div class="recipe-options">
        <div class="option-group">
          <label>食谱类型:</label>
          <select v-model="recipeType" class="recipe-select">
            <option value="all">全部</option>
            <option value="breakfast">早餐</option>
            <option value="lunch">午餐</option>
            <option value="dinner">晚餐</option>
            <option value="vegetarian">素食</option>
          </select>
        </div>
        <div class="option-group">
          <label>难度等级:</label>
          <select v-model="difficultyLevel" class="recipe-select">
            <option value="easy">简单</option>
            <option value="medium">中等</option>
            <option value="hard">困难</option>
          </select>
        </div>
      </div>
      
      <!-- 常用食材标签 -->
      <div class="ingredient-tags">
        <span 
          v-for="(tag, index) in commonIngredients" 
          :key="index" 
          class="ingredient-tag"
          @click="addIngredientTag(tag)"
        >
          {{ tag }}
        </span>
      </div>
      <div class="input-container">
        <input 
          ref="inputField"
          v-model="ingredients"
          @input="handleInput"
          placeholder="请输入食材，用英文逗号分隔"
          maxlength="100"
          class="ingredient-input"
        />
        <span class="char-counter">{{ ingredients.length }}/100</span>
        <button 
          v-if="ingredients" 
          @click="clearInput"
          class="clear-btn"
        >
          ×
        </button>
      </div>
      <div class="button-group">
        <button 
          @click="generateRecipe" 
          :disabled="!ingredients"
          class="generate-btn"
        >
          生成食谱
        </button>
        <button 
          @click="useExample" 
          class="example-btn"
        >
          使用示例
        </button>
        <button 
          @click="showHistoryDialog = true" 
          class="history-btn"
        >
          历史记录
        </button>
      </div>
    </div>

    <!-- 遮罩层 -->
    <div v-if="loading" class="overlay">
      <div class="loading-spinner">正在生成食谱...</div>
    </div>

    <!-- 结果展示 -->
    <div v-if="recipe" class="result-section">
      <div class="recipe-header">
        <h2>{{ recipe.name }}</h2>
        <div class="recipe-meta">
          <span class="recipe-type">{{ recipeTypeNames[recipeType] }}</span>
          <span class="difficulty-badge" :class="difficultyLevel">
            {{ difficultyNames[difficultyLevel] }}
          </span>
        </div>
      </div>
      
      <div class="ingredients-list">
        <h3>所需食材:</h3>
        <ul>
          <li v-for="(item, index) in recipe.ingredients" :key="index">
            {{ item }}
          </li>
        </ul>
      </div>
      
      <div class="steps">
        <h3>制作步骤:</h3>
          <span v-for="(step, index) in recipe.steps" :key="index" >
            <div v-html="build(step)"></div>
          </span>
      </div>
      <div v-if="stepImages.length > 0" class="step-images">
        <img 
          v-for="(img, index) in stepImages" 
          :key="index" 
          :src="img" 
          :alt="'三明治成品图'"
          ref="recipeImage"
          class="recipe-result-image"
        />
      </div>
      
      <div class="action-buttons">
        <button @click="saveToHistory" class="save-btn">保存记录</button>
        <button @click="shareRecipe" class="share-btn">分享</button>
        <button @click="saveAsImage" class="print-btn">保存图片</button>
      </div>
    </div>
    
    <!-- 错误提示 -->
    <div v-if="error" class="error-toast">
      {{ error }}
    </div>
    
    <!-- 历史记录弹窗 -->
    <div v-if="showHistoryDialog" class="history-dialog-overlay">
      <div class="history-dialog">
        <div class="history-dialog-header">
          <h3>历史记录</h3>
          <button class="close-btn" @click="showHistoryDialog = false">×</button>
        </div>
        <div class="history-dialog-content">
          <div v-if="history.length === 0" class="no-history">
            暂无历史记录
          </div>
          <div v-else class="history-cards">
            <div 
              v-for="(item, index) in history" 
              :key="index" 
              class="history-card"
              @click="loadFromHistory(item)"
            >
              <div class="card-header">
                <div class="card-title">{{ item.recipeName }}</div>
                <div class="card-meta">
                  <span class="card-type" v-if="item.recipeType">{{ recipeTypeNames[item.recipeType] }}</span>
                  <span class="card-difficulty" v-if="item.difficultyLevel" :class="item.difficultyLevel">
                    {{ difficultyNames[item.difficultyLevel] }}
                  </span>
                </div>
              </div>
              <div class="card-ingredients">
                <strong>食材:</strong> {{ item.ingredients }}
              </div>
              <div v-if="item.imageBase64 || item.imageUrl" class="card-image">
                <img :src="item.imageBase64 || item.imageUrl" alt="菜谱图片" style="width: 200px;height: 200px;"/>
              </div>
              <div class="card-footer">
                <span class="card-date">{{ item.date }}</span>
                <div class="card-actions">
                  <button class="card-load-btn" @click.stop="loadFromHistory(item)">加载</button>
                  <!-- <button class="card-export-btn" @click.stop="exportRecipeToFile(item)">导出</button> -->
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import Marked from 'marked';
import html2canvas from 'html2canvas';
// 注意：需要安装html2canvas库
// npm install --save html2canvas
import sandwich from '@/assets/sandwich.png';
export default {
  name: 'SandwichGenerator',
  data() {
    return {
      sandwich: sandwich,
      // 当前主题，从localStorage获取或使用默认主题
      currentTheme: localStorage.getItem('sandwichTheme') || 'theme-default',
      // 暗黑模式状态
      isDarkMode: localStorage.getItem('sandwichDarkMode') === 'true',
      // 显示历史记录弹窗
      showHistoryDialog: false,
      // 食谱类型
      recipeType: 'all',
      // 食谱难度
      difficultyLevel: 'medium',
      // 食谱类型名称映射
      recipeTypeNames: {
        all: '全部类型',
        breakfast: '早餐',
        lunch: '午餐',
        dinner: '晚餐',
        vegetarian: '素食'
      },
      // 难度等级名称映射
      difficultyNames: {
        easy: '简单',
        medium: '中等',
        hard: '困难'
      },
      // 主题列表配置
      themeList: [
        { name: '默认主题', value: 'theme-default' },
        { name: '美食主题', value: 'theme-food' },
        { name: '清新主题', value: 'theme-fresh' },
        { name: '温馨主题', value: 'theme-warm' }
      ],
      // 常用食材标签
      commonIngredients: ['鸡蛋', '番茄', '生菜', '火腿', '芝士', '牛肉', '鸡肉', '培根', '黄瓜', '洋葱'],
      // 示例食材组合
      exampleIngredients: [
        '大米,饺子,青菜叶'
       
      ],
      // 当前输入的食材
      ingredients: '',
      // 加载状态标识
      loading: false,
      // 生成的食谱数据
      recipe: null,
      // 食谱步骤图片列表
      stepImages: [],
      // 错误信息
      error: null,
      // 历史记录
      history: []
    }
  },
  mounted() {
    this.$refs.inputField.focus();
    this.loadHistory();
  },
  methods: {
    build(step) {
      return Marked.parse(step);
    },
    selectTheme(theme) {
      this.currentTheme = theme;
      localStorage.setItem('sandwichTheme', theme);
      this.showToast('主题已切换');
    },
    handleInput() {
      if (this.ingredients.length > 100) {
        this.ingredients = this.ingredients.substring(0, 100);
      }
    },
    clearInput() {
      this.ingredients = '';
    },
    addIngredientTag(tag) {
      // 如果已有内容，添加逗号分隔
      if (this.ingredients && this.ingredients.trim() !== '') {
        // 检查最后一个字符是否已经是逗号
        if (this.ingredients.trim().slice(-1) === ',') {
          this.ingredients = this.ingredients.trim() + ' ' + tag;
        } else {
          this.ingredients = this.ingredients.trim() + ', ' + tag;
        }
      } else {
        this.ingredients = tag;
      }
      // 聚焦输入框
      this.$refs.inputField.focus();
    },
    
    // 切换暗黑模式
    toggleDarkMode() {
      this.isDarkMode = !this.isDarkMode;
      localStorage.setItem('sandwichDarkMode', this.isDarkMode);
      this.showToast(this.isDarkMode ? '已切换到暗黑模式' : '已切换到明亮模式');
    },
    
    // 保存食谱为图片
    saveAsImage() {
      if (!this.recipe) return;
      
      try {
        // 创建一个新的HTML元素来渲染食谱
        const recipeEl = document.createElement('div');
        recipeEl.className = 'recipe-print';
        recipeEl.style.padding = '20px';
        recipeEl.style.backgroundColor = 'white';
        recipeEl.style.maxWidth = '800px';
        recipeEl.style.margin = '0 auto';
        
        // 添加食谱标题和标签
        recipeEl.innerHTML = `
          <h1 style="color:#4CAF50;text-align:center;margin-bottom:15px;">${this.recipe.name}</h1>
          <div style="display:flex;justify-content:center;gap:15px;margin-bottom:20px;">
            <span style="background-color:#E3F2FD;color:#1565C0;padding:4px 8px;border-radius:4px;">${this.recipeTypeNames[this.recipeType]}</span>
            <span style="background-color:${this.difficultyLevel === 'easy' ? '#C8E6C9' : this.difficultyLevel === 'medium' ? '#FFE0B2' : '#FFCDD2'};
                  color:${this.difficultyLevel === 'easy' ? '#2E7D32' : this.difficultyLevel === 'medium' ? '#E65100' : '#C62828'};
                  padding:4px 8px;border-radius:4px;">
              难度: ${this.difficultyNames[this.difficultyLevel]}
            </span>
          </div>
        `;
        
        // 添加食材和步骤
        const contentDiv = document.createElement('div');
        contentDiv.innerHTML = `
          <h2 style="color:#333;border-bottom:1px solid #eee;padding-bottom:8px;">所需食材:</h2>
          <ul style="padding-left:20px;">
            ${this.recipe.ingredients.map(item => `<li style="margin-bottom:5px;">${item}</li>`).join('')}
          </ul>
          <h2 style="color:#333;border-bottom:1px solid #eee;padding-bottom:8px;margin-top:20px;">制作步骤:</h2>
          <div style="line-height:1.6;">${this.recipe.steps.map(step => Marked.parse(step)).join('')}</div>
        `;
        recipeEl.appendChild(contentDiv);
        
        // 如果有图片，添加图片（放在最下面）
        if (this.stepImages.length > 0) {
          const imgContainer = document.createElement('div');
          imgContainer.style.textAlign = 'center';
          imgContainer.style.marginTop = '25px';
          imgContainer.style.marginBottom = '10px';
          
          const img = document.createElement('img');
          img.src = this.stepImages[0];
          img.style.maxWidth = '90%';
          img.style.borderRadius = '8px';
          img.style.boxShadow = '0 4px 8px rgba(0,0,0,0.2)';
          img.style.maxHeight = '350px';
          img.crossOrigin = 'anonymous'; // 添加跨域支持
          
          imgContainer.appendChild(img);
          recipeEl.appendChild(imgContainer);
        }
        
        // 将元素添加到文档中
        document.body.appendChild(recipeEl);
        
        // 使用html2canvas将元素转换为图片，添加延迟确保图片加载完成
        setTimeout(() => {
          html2canvas(recipeEl, {
            useCORS: true, // 允许跨域图片
            allowTaint: true, // 允许跨域图片
            logging: true // 启用日志以便调试
          }).then(canvas => {
            // 创建下载链接
            const link = document.createElement('a');
            link.download = `${this.recipe.name}.png`;
            link.href = canvas.toDataURL('image/png');
            link.click();
            
            // 移除临时元素
            document.body.removeChild(recipeEl);
            
            this.showToast('食谱图片已保存');
          }).catch(err => {
            console.error('保存图片失败:', err);
            this.showError('保存图片失败，请重试');
            document.body.removeChild(recipeEl);
          });
        }, 500); // 给图片500毫秒的加载时间
      } catch (error) {
        console.error('保存图片失败:', error);
        this.showError('保存图片失败，请重试');
      }
    },
    useExample() {
      const randomIndex = Math.floor(Math.random() * this.exampleIngredients.length);
      this.ingredients = this.exampleIngredients[randomIndex];

      const content = "\n\n### 饺子与青菜饭团三明治食谱  \n**特点**：将传统饺子与米饭结合，搭配清脆青菜，制作一款咸香多汁的中式风味三明治。  \n\n---\n\n#### **食材**  \n（2人份）  \n- **饺子** 10个（煮熟后切碎）  \n- **米饭** 1碗（隔夜冷饭最佳，或煮熟后晾凉）  \n- **青菜叶** 4-5片（如生菜、油麦菜或菠菜叶）  \n- **面包片** 4片（全麦或吐司面包）  \n- **酱料**：沙拉酱/千岛酱 2大勺，酱油 1小勺，芝麻油 1小勺  \n- **调味料**：盐、黑胡椒、白芝麻（可选）  \n\n---\n\n#### **步骤**  \n1. **预处理食材**  \n   - **煮饺子**：将饺子沸水煮熟（约5分钟），捞出沥干后切碎。  \n   - **炒饭调味**：将米饭与酱油、芝麻油、少许盐和黑胡椒混合拌匀（可加入少许煎香的葱花提香）。  \n   - **煎饺子碎**（可选）：在平底锅中加入少许油，将切碎的饺子煎至边缘微焦，增加香气。  \n\n2. **组装三明治**  \n   - **预热面包**：将面包片放入烤箱或平底锅中煎至两面微焦，增加酥脆口感。  \n   - **涂抹酱料**：在面包片上均匀涂抹沙拉酱或千岛酱。  \n   - **铺青菜叶**：放上洗净沥干的青菜叶（如生菜叶），增加清新口感。  \n   - **夹入馅料**：  \n          第一层：铺上拌好的调味米饭。  \n          第二层：放上煎过的饺子碎。  \n          可撒上黑胡椒或白芝麻增香。  \n   - **盖上面包**：将另一片面包盖上，轻轻压实。  \n\n3. **切块与享用**  \n   - 将三明治对角切开，方便食用。  \n   - 配搭蘸酱（如酱油混合少许芝麻油）享用，"
        this.recipe =  {
          name: 'AI生成三明治',
          ingredients: this.ingredients.split(',').map(i => i.trim()),
          steps: content.split('\n')
        };

        const response = JSON.parse(`{
    "images": [
        {
            "url": "${sandwich}"
        }
    ],
    "timings": {
        "inference": 0.672
    },
    "seed": 366266646,
    "shared_id": "0",
    "data": [
        {
            "img": "${process.env.BASE_URL}/assets/sandwich.png"
        }
    ],
    "created": 1747575648
}`)
        this.stepImages = response.images.map(img => img.url);
        console.log(this.stepImages);
    },
    async generateRecipe() {
      this.loading = true;
      this.error = null;
      
      try {
        // 调用API生成食谱
        const recipeResponse = await this.callRecipeAPI();
        
        if (!recipeResponse || Object.keys(recipeResponse).length === 0) {
          throw new Error('没有找到合适食谱');
        }
        
        this.recipe = recipeResponse;
        
        // 调用大模型生成最终成品图片
        try {
          const finalImage = await this.generateFinalImage();
          this.stepImages = finalImage;
        } catch (imgError) {
          console.error('成品图生成失败:', imgError);
          this.stepImages = [];
        }
        
      } catch (error) {
        this.showError(error.message || '网络连接失败，请重试');
      } finally {
        this.loading = false;
      }
    },
    async callRecipeAPI() {
      try {
        // 构建提示词，包含食材、食谱类型和难度
        let prompt = `根据以下食材生成一个三明治食谱: ${this.ingredients}`;
        
        // 添加食谱类型
        if (this.recipeType !== 'all') {
          prompt += `，这是一个${this.recipeTypeNames[this.recipeType]}食谱`;
        }
        
        // 添加难度要求
        prompt += `，难度级别为${this.difficultyNames[this.difficultyLevel]}`;
        
        // 要求生成创意名称
        prompt += `。请为这个三明治创建一个有创意的名称，并在食谱开头以"【三明治名称】：XXX"的格式展示。`;
        
        const response = await axios.post('https://api.siliconflow.cn/v1/chat/completions', {
          //model: 'deepseek-ai/DeepSeek-R1-Distill-Qwen-32B',
          model: 'deepseek-ai/DeepSeek-V3',
          messages: [{
            role: 'user',
            content: prompt
          }],
          stream: false,
          max_tokens: 512,
          temperature: 0.8 // 稍微提高创意性
        }, {
          headers: {
            Authorization: 'Bearer ' + process.env.VUE_APP_API_KEY,
            'Content-Type': 'application/json'
          }
        });
        
        const content = response.data.choices[0].message.content;
        
        // 尝试从内容中提取创意名称
        let recipeName = '创意三明治';
        const nameMatch = content.match(/【三明治名称】：(.+?)[\n\r]/);
        if (nameMatch && nameMatch[1]) {
          recipeName = nameMatch[1].trim();
        } else {
          // 尝试匹配其他可能的格式
          const altMatch = content.match(/[「『"【《]([^「『"【《」』"】》]+)[」』"】》]/);
          if (altMatch && altMatch[1]) {
            recipeName = altMatch[1].trim();
          } else {
            // 尝试匹配第一行作为标题
            const firstLine = content.split('\n')[0].trim();
            if (firstLine && firstLine.length < 30) { // 确保不是太长的内容
              recipeName = firstLine.replace(/[:#：：]/g, '').trim(); // 移除可能的标点符号
            }
          }
        }
        
        return {
          name: recipeName,
          ingredients: this.ingredients.split(',').map(i => i.trim()),
          steps: content.split('\n')
        };
      } catch (error) {
        throw new Error('食谱生成失败: ' + error.message);
      }
    },
    async generateFinalImage() {
      try {
        const response = await axios.post('https://api.siliconflow.cn/v1/images/generations', {
          model: 'Kwai-Kolors/Kolors',
          prompt: `根据以下食谱生成三明治成品图片: ${JSON.stringify(this.recipe)}`,
          negative_prompt: '',
          image_size: '1024x1024',
          batch_size: 1,
          seed: Math.floor(Math.random() * 1000000000),
          num_inference_steps: 20,
          guidance_scale: 7.5
        }, {
          headers: {
            Authorization: 'Bearer ' + process.env.VUE_APP_API_KEY,
            'Content-Type': 'application/json'
          }
        });
        
        // 获取图片URL
        const imageUrls = response.data.images.map(img => img.url);
        
        // 如果有图片，将其转换为base64
        if (imageUrls.length > 0) {
          try {
            // 预加载并转换为base64
            const base64Images = await Promise.all(
              imageUrls.slice(0, 1).map(url => this.convertImageToBase64(url))
            );
            return base64Images;
          } catch (conversionError) {
            console.error('图片转换失败:', conversionError);
            return imageUrls; // 如果转换失败，返回原始URL
          }
        }
        return imageUrls;        
      } catch (error) {
        console.error('图片生成失败:', error);
        return [];
      }
    },
    
    // 预加载图片的辅助方法
    preloadImage(src) {
      return new Promise((resolve, reject) => {
        const img = new Image();
        img.crossOrigin = 'anonymous'; // 设置跨域
        img.onload = () => resolve(img);
        img.onerror = (e) => {
          console.error('图片加载失败:', e);
          reject(e);
        };
        img.src = src;
      });
    },
    
    // 将图片URL转换为base64
    async convertImageToBase64(imageUrl) {
      try {
        // 加载图片
        const img = await this.preloadImage(imageUrl);
        
        // 创建canvas并绘制图片
        const canvas = document.createElement('canvas');
        canvas.width = img.width;
        canvas.height = img.height;
        const ctx = canvas.getContext('2d');
        ctx.drawImage(img, 0, 0);
        
        // 转换为base64，使用较低质量的JPEG格式以减小大小
        const base64Data = canvas.toDataURL('image/jpeg', 0.7);
        return base64Data;
      } catch (error) {
        console.error('图片转base64失败:', error);
        throw error;
      }
    },
    showError(message) {
      this.error = message;
      setTimeout(() => {
        this.error = null;
      }, 3000);
    },
    saveToHistory() {
      if (!this.recipe) return;
      
      // 保存完整的菜谱信息，包括base64格式的图片
      const record = {
        date: new Date().toLocaleString(),
        ingredients: this.ingredients,
        recipeName: this.recipe.name,
        recipeType: this.recipeType,
        difficultyLevel: this.difficultyLevel,
        // 保存完整菜谱内容
        fullRecipe: {
          name: this.recipe.name,
          ingredients: this.recipe.ingredients,
          steps: this.recipe.steps
        },
        // 保存base64格式的图片（如果有）
        imageBase64: this.stepImages.length > 0 ? this.stepImages[0] : null
      };
      
      this.history.unshift(record);
      if (this.history.length > 10) { // 增加历史记录上限
        this.history.pop();
      }
      
      // 保存到localStorage
      try {
        localStorage.setItem('sandwichHistory', JSON.stringify(this.history));
        this.showToast('菜谱已保存到历史记录');
      } catch (e) {
        // 如果localStorage存储失败（可能是因为数据太大）
        console.error('保存到localStorage失败:', e);
        // 移除图片数据后再尝试保存
        const historyWithoutImages = this.history.map(item => {
          const { imageBase64, ...rest } = item;
          return rest;
        });
        localStorage.setItem('sandwichHistory', JSON.stringify(historyWithoutImages));
        this.showError('图片太大无法保存，仅保存了菜谱内容');
      }
    },
    
    // 导出菜谱到本地文件
    exportRecipeToFile(recipeRecord) {
      try {
        // 创建Blob对象
        const recipeBlob = new Blob(
          [JSON.stringify(recipeRecord, null, 2)], 
          {type: 'application/json'}
        );
        
        // 创建下载链接
        const link = document.createElement('a');
        link.href = URL.createObjectURL(recipeBlob);
        link.download = `${recipeRecord.recipeName.replace(/[\\/:*?"<>|]/g, '_')}_${new Date().getTime()}.json`;
        
        // 触发下载
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      } catch (error) {
        console.error('导出菜谱失败:', error);
        this.showError('导出菜谱失败，请重试');
      }
    },
    loadHistory() {
      const saved = localStorage.getItem('sandwichHistory');
      if (saved) {
        this.history = JSON.parse(saved);
      }
    },
    loadFromHistory(historyItem) {
      this.ingredients = historyItem.ingredients;
      this.recipeType = historyItem.recipeType || 'all';
      this.difficultyLevel = historyItem.difficultyLevel || 'medium';
      this.showHistoryDialog = false;
      
      // 如果有完整菜谱，直接加载
      if (historyItem.fullRecipe) {
        this.recipe = historyItem.fullRecipe;
        // 优先加载base64格式的图片，其次加载URL格式的图片
        if (historyItem.imageBase64) {
          this.stepImages = [historyItem.imageBase64];
        } else if (historyItem.imageUrl) {
          this.stepImages = [historyItem.imageUrl];
        } else {
          this.stepImages = [];
        }
      } else {
        // 否则重新生成
        this.generateRecipe();
      }
    },
    
    shareRecipe() {
      const url = window.location.href;
      
      if (navigator.share) {
        navigator.share({
          title: this.recipe.name,
          text: '查看我用创意三明治生成器制作的食谱！',
          url: url
        }).catch(error => {
          console.error('分享失败:', error);
          this.copyToClipboard(url);
        });
      } else {
        this.copyToClipboard(url);
      }
    },
    
    copyToClipboard(text) {
      const input = document.createElement('input');
      input.value = text;
      document.body.appendChild(input);
      input.select();
      document.execCommand('copy');
      document.body.removeChild(input);
      this.showError('链接已复制到剪贴板');
    },
    
    showToast(message) {
      this.error = message;
      setTimeout(() => {
        this.error = null;
      }, 3000);
    }
  }
}
</script>

<style scoped>
/* 主题样式 */
.sandwich-generator.theme-default {
  background-color: #f9f9f9;
  color: #333;
}

.sandwich-generator.theme-food {
  background-color: #fff8f0;
  color: #5a3e36;
}

.sandwich-generator.theme-fresh {
  background-color: #f0fff4;
  color: #2d5e4a;
}

.sandwich-generator.theme-warm {
  background-color: #fff0f0;
  color: #6d3b47;
}

/* 暗黑模式 */
.sandwich-generator.dark-mode {
  background-color: #1a1a1a;
  color: #e0e0e0;
}

.dark-mode .app-intro {
  background-color: rgba(40, 40, 40, 0.9);
}

.dark-mode .app-intro h1 {
  color: #66bb6a;
}

.dark-mode .app-intro p {
  color: #e0e0e0;
}

.dark-mode .ingredient-input,
.dark-mode .recipe-select {
  background-color: #333;
  color: #e0e0e0;
  border-color: #555;
}

.dark-mode .ingredient-tag {
  background-color: #2c3e50;
  color: #4CAF50;
  border-color: #4CAF50;
}

.dark-mode .result-section {
  background-color: #2a2a2a;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
}

.dark-mode .history-dialog {
  background-color: #2a2a2a;
}

.dark-mode .history-card {
  background-color: #333;
  border-color: #444;
}

.app-intro {
  text-align: center;
  margin-bottom: 20px;
  padding: 20px;
  background-color: rgba(255,255,255,0.9);
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.app-intro h1 {
  color: #4CAF50;
  margin-bottom: 15px;
}

.app-intro p {
  margin: 8px 0;
  color: #333;
  line-height: 1.6;
}

.theme-icon {
  font-size: 24px;
  cursor: pointer;
  margin: 0 5px;
  transition: transform 0.3s;
}

.theme-icon:hover {
  transform: scale(1.2);
}

.sandwich-generator {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
  font-family: 'Roboto', sans-serif;
}

.input-section {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-bottom: 20px;
  margin-top: 20px;
}

.input-container {
  position: relative;
}

.ingredient-input {
  width: 100%;
  padding: 12px 40px 12px 15px;
  border: 2px solid #4CAF50;
  border-radius: 8px;
  font-size: 16px;
  transition: all 0.3s;
  background-color: rgba(255, 255, 255, 0.8);
}

.ingredient-input:focus {
  background-color: white;
  border-color: #2E7D32;
}

.ingredient-input:focus {
  border-color: #2E7D32;
  box-shadow: 0 0 0 2px rgba(76, 175, 80, 0.2);
  transform: scale(1.01);
}

.ingredient-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 12px;
}

.ingredient-tag {
  background-color: #E8F5E9;
  color: #2E7D32;
  padding: 6px 12px;
  border-radius: 16px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s;
  border: 1px solid #A5D6A7;
}

.ingredient-tag:hover {
  background-color: #C8E6C9;
  transform: translateY(-2px);
}

/* 食谱选项样式 */
.recipe-options {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
  flex-wrap: wrap;
  gap: 10px;
}

.option-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.option-group label {
  font-weight: 500;
  white-space: nowrap;
}

.recipe-select {
  padding: 8px 12px;
  border-radius: 6px;
  border: 1px solid #ddd;
  background-color: white;
  font-size: 14px;
  min-width: 100px;
}

/* 难度标签样式 */
.difficulty-badge {
  display: inline-block;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
  margin-left: 10px;
}

.difficulty-badge.easy {
  background-color: #C8E6C9;
  color: #2E7D32;
}

.difficulty-badge.medium {
  background-color: #FFE0B2;
  color: #E65100;
}

.difficulty-badge.hard {
  background-color: #FFCDD2;
  color: #C62828;
}

/* 食谱头部样式 */
.recipe-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.recipe-meta {
  display: flex;
  align-items: center;
  gap: 10px;
}

.recipe-type {
  background-color: #E3F2FD;
  color: #1565C0;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

/* 历史卡片样式 */
.history-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 15px;
}

.history-card {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  padding: 15px;
  cursor: pointer;
  transition: all 0.3s;
  border: 1px solid #eee;
  display: flex;
  flex-direction: column;
}

.history-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0,0,0,0.15);
}

.card-header {
  margin-bottom: 10px;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.card-title {
  font-weight: bold;
  font-size: 16px;
  color: #333;
}

.card-meta {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 5px;
}

.card-type {
  font-size: 12px;
  background-color: #E3F2FD;
  color: #1565C0;
  padding: 2px 6px;
  border-radius: 4px;
}

.card-difficulty {
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 4px;
}

.card-ingredients {
  margin: 10px 0;
  font-size: 14px;
  color: #555;
  flex-grow: 1;
}

.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}

.card-date {
  font-size: 12px;
  color: #888;
}

.card-load-btn {
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 4px 8px;
  font-size: 12px;
  cursor: pointer;
}

.char-counter {
  position: absolute;
  right: 50px;
  top: 50%;
  transform: translateY(-50%);
  color: #757575;
  font-size: 14px;
}

/* 打印按钮样式 */
.print-btn {
  background-color: #673AB7;
  color: white;
  padding: 10px 20px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  min-height: 44px;
  min-width: 100px;
  transition: all 0.3s;
}

.print-btn:hover {
  background-color: #5E35B1;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0,0,0,0.2);
}

/* 打印样式 */
.recipe-print {
  font-family: 'Arial', sans-serif;
  color: #333;
  line-height: 1.6;
  box-shadow: 0 4px 12px rgba(0,0,0,0.15);
  border-radius: 8px;
  overflow: hidden;
}

.clear-btn {
  position: absolute;
  right: 15px;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  font-size: 20px;
  color: #757575;
  cursor: pointer;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
}

.clear-btn:hover {
  background-color: #f5f5f5;
}

.generate-btn {
  padding: 12px 24px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  cursor: pointer;
  min-height: 44px;
  min-width: 120px;
  transition: all 0.3s;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.generate-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 8px rgba(0, 0, 0, 0.15);
}

.generate-btn:hover {
  background-color: #388E3C;
}

.generate-btn:disabled {
  background-color: #BDBDBD;
  cursor: not-allowed;
}

.overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  animation: fadeIn 0.3s;
}

.loading-spinner {
  background-color: white;
  padding: 20px 30px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.result-section {
    text-align: left;
  margin-top: 30px;
  animation: fadeIn 0.5s;
}

.ingredients-list,
.steps {
  margin: 20px 0;
}

.step-images {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin: 20px 0;
}

.step-images img {
  max-width: 100%;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.recipe-result-image {
  max-height: 350px;
  object-fit: contain;
  margin: 0 auto;
  display: block;
}

.action-buttons {
    text-align: center;
  display: flex;
  gap: 10px;
  margin-top: 20px;
  justify-content: center;
}

.button-group {
  display: flex;
  gap: 10px;
  margin-top: 10px;
  justify-content: center;
  width: 100%;
}

.example-btn {
  padding: 12px 24px;
  background-color: #2196F3;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  cursor: pointer;
  min-height: 44px;
  min-width: 120px;
  transition: all 0.3s;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.example-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 8px rgba(0, 0, 0, 0.15);
  background-color: #1976D2;
}

.history-btn {
  padding: 12px 24px;
  background-color: #9C27B0;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  cursor: pointer;
  min-height: 44px;
  min-width: 120px;
  transition: all 0.3s;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.history-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 8px rgba(0, 0, 0, 0.15);
  background-color: #7B1FA2;
}

.save-btn,
.share-btn {
  padding: 10px 20px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  min-height: 44px;
  min-width: 100px;
}

.save-btn {
  background-color: #2196F3;
  color: white;
}

.share-btn {
  background-color: #FF9800;
  color: white;
}

.error-toast {
  position: fixed;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  background-color: #F44336;
  color: white;
  padding: 12px 24px;
  border-radius: 4px;
  box-shadow: 0 3px 5px rgba(0, 0, 0, 0.2);
  animation: fadeIn 0.3s, fadeOut 0.3s 2.7s;
  z-index: 1000;
}

/* 历史记录弹窗样式 */
.history-dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1001;
  animation: fadeIn 0.3s;
}

.history-dialog {
  background-color: white;
  width: 90%;
  max-width: 500px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  max-height: 80vh;
  display: flex;
  flex-direction: column;
}

.history-dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
}

.history-dialog-header h3 {
  margin: 0;
  color: #4CAF50;
}

.history-dialog-content {
  padding: 20px;
  overflow-y: auto;
  max-height: 60vh;
}

.no-history {
  text-align: center;
  color: #757575;
  padding: 20px 0;
}

.history-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.history-item {
  padding: 15px;
  border-radius: 8px;
  background-color: #f9f9f9;
  cursor: pointer;
  transition: all 0.2s;
  border-left: 4px solid #4CAF50;
}

.history-item:hover {
  background-color: #f0f0f0;
  transform: translateY(-2px);
}

.history-item-name {
  font-weight: bold;
  margin-bottom: 5px;
  color: #333;
}

.history-item-ingredients {
  color: #555;
  margin-bottom: 5px;
  font-size: 14px;
}

.history-item-date {
  color: #888;
  font-size: 12px;
  text-align: right;
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

@keyframes fadeOut {
  from { opacity: 1; }
  to { opacity: 0; }
}

@media (max-width: 600px) {
  .theme-icon {
  font-size: 24px;
  cursor: pointer;
  margin: 0 5px;
  transition: transform 0.3s;
}

.theme-icon:hover {
  transform: scale(1.2);
}

.sandwich-generator {
    padding: 15px;
  }
  
  .ingredient-input {
    padding: 10px 0px 10px 0px;
  }
  
  .button-group {
    flex-direction: column;
    gap: 10px;
  }
  
  .generate-btn,
  .example-btn,
  .history-btn {
    width: 100%;
  }
}
</style>